package main

// A quote server.
// This software is under GPL v3 license.
// Copyright 2012 Cédric Bonhomme - http://cedricbonhomme.org/

import (
        "fmt"
        "os"
        "io/ioutil"
        "encoding/xml"
        "math/rand"
        "time"
)

// Quotes are store in an array of Quote object.
type Quotes struct {
    Quotes    []Quote    `xml:"quote"`
}

// Defintion of the structure of a Quote object.
type Quote struct {
    Citation string    `xml:"citation"`
    Author    string    `xml:"author"`
    Year   string `xml:"year"`
}

// Read a file and return a string.
func read(file_name string) string {
    inputFile := file_name
    buf, err := ioutil.ReadFile(inputFile)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
    }
    return string(buf)
}

// Check if an error occured
func checkError(err error) int {
    if err != nil {
        os.Stdout.WriteString("Content-type:text/html\r\n\r\n")
        os.Stdout.WriteString("<!DOCTYPE html>\n<html>\n<head>\n<title>GoQuotes</title>\n")
        os.Stdout.WriteString("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n")
        os.Stdout.WriteString("<link rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" />\n</head>\n")
        os.Stdout.WriteString("<body>\n")
        os.Stdout.WriteString("Error " + err.Error())
        os.Stdout.WriteString("</body>\n</html>")
        return 1
    }
    return 0
}

// Return a random quote.
func getQuote(file_name string) {
    quotes_str := read(file_name)
    var quotes Quotes

    err := xml.Unmarshal([]byte(quotes_str), &quotes)
    if (1 != checkError(err)) {
        // Get the number of quotes
        nb_quotes := len(quotes.Quotes)
        rand.Seed(time.Now().UnixNano())
        quote := rand.Intn(nb_quotes)

        // Now use the Quote structure
        printHTML(quotes.Quotes[quote])
    }
}

// Print the quote (citation + author + date)
func printHTML(quote Quote) {
    os.Stdout.WriteString("Content-type:text/html\r\n\r\n")
    os.Stdout.WriteString("<!DOCTYPE html>\n<html>\n<head>\n<title>GoQuotes</title>\n")
    os.Stdout.WriteString("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n")
    os.Stdout.WriteString("<link rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" />\n</head>\n")
    os.Stdout.WriteString("<body>\n")
    os.Stdout.WriteString("<blockquote>\"" + quote.Citation + "\"</blockquote>\n")
    os.Stdout.WriteString(quote.Author)
    if len(quote.Year) != 0 {
        os.Stdout.WriteString(" - " + quote.Year + "\n")
    } else {
        os.Stdout.WriteString("\n")
    }
    os.Stdout.WriteString("<!-- Generated with GoQuotes (https://bitbucket.org/cedricbonhomme/goquotes) -->\n")
    os.Stdout.WriteString("</body>\n</html>")
}

// Main: you can specify here the location of the XML file of quotes.
func main() {
    getQuote("./quotes.xml")
}
